<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use Illuminate\Http\Request;
use DB;

class AdminController extends BaseController
{
    public function index()
    {
        $admins = DB::table('admin')->where('status', '<>', 99)->paginate();
        return view('admin.admin.index', compact('admins'));
    }

    public function create()
    {
        return view('admin.admin.create');
    }

    public function store(Request $request)
    {
        if (DB::table('admin')->where('username', $request->username)->where('status', '<>', 99)->first()) {
            return jsonFailed('该用户名已存在');
        }
        $data = $this->setCreateUpdateParams($request->all());
        DB::table('admin')->insert($data);
        return jsonSuccess();
    }

    public function edit(Request $request)
    {
        $admin = DB::table('admin')->where('id', $request->id)->first();
        return view('admin.admin.edit', compact('admin'));
    }

    public function update(Request $request)
    {
        if (DB::table('admin')->where('username', $request->username)->where('status', '<>', 99)->where('id', '<>', $request->id)->first()) {
            return jsonFailed('该用户名已存在');
        }
        $data = $this->setCreateUpdateParams($request->all());
        DB::table('admin')->where('id', $request->id)->update($data);
        return jsonSuccess();
    }

    private function setCreateUpdateParams($params = [])
    {
        $data = [];
        if (isset($params['username'])) $data['username'] = $params['username'];
        if (isset($params['password']) && !empty($params['password'])) {
            $data['password'] = md5($params['password']);
        }
        if (isset($params['description'])) $data['description'] = $params['description'];
        if (isset($params['status'])) $data['status'] = $params['status'];
        return $data;
    }

    public function delete(Request $request)
    {
        if ($request->id == 1) return jsonFailed('超级管理员不能被删除');
        DB::table('admin')->where(['id' => $request->id])->update(['status' => 99]);
        return jsonSuccess();
    }
}
